package com.ejuornal.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.dao.EmptyResultDataAccessException;

import com.ejuornal.bean.Ads;
import com.ejuornal.bean.Artical;
import com.ejuornal.bean.Board;
import com.ejuornal.bean.Category;
import com.ejuornal.bean.PerPeriodical;
import com.ejuornal.bean.Periodical;
import com.ejuornal.bean.UserExt;
import com.ejuornal.service.AdsService;
import com.ejuornal.service.ArticalService;
import com.ejuornal.service.BoardService;
import com.ejuornal.service.CategoryService;
import com.ejuornal.service.PerPeriodicalService;
import com.ejuornal.service.PeriodicalService;
import com.ejuornal.service.UserExtService;
import com.ejuornal.springutil.SpringUtil;
import com.google.gson.Gson;

public class PeriodicalAction extends BaseAction<Periodical> {
	private static final long serialVersionUID = 1L;
	private PeriodicalService periodicalService = null;
	private Periodical periodical = null;
	private PerPeriodicalService perPeriodicalService;
	private List<Periodical> periodicals;
	private String value;
	private File upload;
	private String uploadFileName;
	private List<Artical> articals;
	private ArticalService articalService;
	private String allPeriodicalInfo;//根据主编id得到管理所有期刊
	private Map<String, Object> dataMap = new HashMap<String, Object>();
	private Ads ads_Category;
	private AdsService adsService;
	
	/**
	 * 创建期刊，完成后跳转到“我的期刊”页面，并创建第一期期刊
	 * @author syb
	 * @return
	 */
	public String addPeriodical() {
		String realPath = ServletActionContext.getServletContext().getRealPath("/attached/images");
		String dbPicSrc = null;//存储路径
		if(upload != null){
			File saveDir = new File(realPath);
			//图片重命名
			String ext = uploadFileName.split("\\.")[1];//后缀名
			Calendar cal = Calendar.getInstance();
			String reName = String.valueOf(cal.getTimeInMillis());
			dbPicSrc = "attached/images/"+reName+"."+ext;
			uploadFileName = reName+"."+ext;
			
			if(saveDir.exists()){
				File saveFile = new File(saveDir, uploadFileName);
				try {
					FileUtils.copyFile(upload, saveFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			else{
				saveDir.mkdirs();
				File saveFile = new File(saveDir, uploadFileName);
				try {
					FileUtils.copyFile(upload, saveFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		periodical.setCover(dbPicSrc);
		periodical.setUserId(super.getUserIdBySession());
		periodical.setCreateDate(new Date());
		periodical.setStatus("0");
		periodicalService.add(periodical);
		
		//查询出刚创建的期刊
		periodical = periodicalService.findByUserIdPStatus(0, null, super.getUserIdBySession(), "0").getRecords().get(0);
		
		//在板块表t_board中添加期刊的板块
		BoardService boardService = (BoardService)SpringUtil.getBean("boardService");
		Board board = new Board();
		String[] name = value.split(" ");
		for(String str:name) {
			board.setName(str);
			board.setPeriodicalId(periodical.getPeriodicalId());
			boardService.add(board);
		}
		
		//创建期刊后立即自动创建第一期期刊
		PerPeriodical perPeriodical = new PerPeriodical();
		perPeriodical.setPeriodicalId(periodical.getPeriodicalId());
		perPeriodical.setNumber(1);
		perPeriodical.setStatus("-1");	//每次发布期刊后都自动生成下期期刊，状态设为-1
		perPeriodicalService.add(perPeriodical);
		
		return "success";
	}
	/**
	 * 查找所有已经审核过的期刊根据类别编号
	 */
	public String findByCateId() {
		int id = super.getRequestParameter();
		if(id == -1) {
			return ERROR;
		}
		periodicals = periodicalService.findByCategoryId(id, "1");
		dataMap.clear();
		dataMap.put("periodicals", periodicals);
		return SUCCESS;
	}
	
	/**
	 * 查询某编辑所属的期刊
	 * @return
	 */
	public String findByEditorId() {
		//value为0，表示查询所有期刊；如果不为0，则查询属于某类的期刊
		periodicals = periodicalService.findByEditorId(super.getUserIdBySession(), "1", Integer.parseInt(value));

		dataMap.clear();
		dataMap.put("periodicals", periodicals);
		
		return "success";
	}
	
    //查询所有的期刊
	public String findAll() {
		String url = "periodical/periodicalAll?";
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		pages = periodicalService.findAll((page-1)*10, url);
		
		return "success";
	}
	
	//根据期刊状态查询
	public String findByStatus() {
		String url = "periodical/periodicalStatus?value=" + value + "&";
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		if("0".equals(value)) {	//查询未审核的期刊
			pages = periodicalService.findByStatus((page-1)*10, url, value);
			return "uncheck";
		} else if("1".equals(value)) {	//查询已审核的期刊
			pages = periodicalService.findByStatus((page-1)*10, url, value);
			return "success";
		} else if("2".equals(value)){	//查询停刊期刊
			pages = periodicalService.findByStatus((page-1)*10, url, value);
			return "stoppublish";
		} else if("3".equals(value)){	//查询未通过期刊
			pages = periodicalService.findByStatus((page-1)*10, url, value);
			return "success";
		} else{
			return "error";	//异常处理
		}
	}
	
	//根据关键字查询期刊
	public String search(){
		String keywords = (String) super.getRequestParameter("keywords");
		periodicals = periodicalService.search(keywords);
		articals = articalService.findByName(keywords);
		List<Artical> recommendArtical = articalService.findTop(10);//文章推荐，读取前10条
		List<Periodical> hotPeriodicals = periodicalService.findTop(10);//热门期刊，读取前10条
		super.getRequest().setAttribute("recommendArtical", recommendArtical);
		super.getRequest().setAttribute("hotPeriodicals", hotPeriodicals);
		return SUCCESS;
	}
	
	public String findById() {
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		periodical = periodicalService.findById(periodical.getPeriodicalId());
		UserExtService userExtService = (UserExtService)SpringUtil.getBean("userExtService");
		UserExt userExt = userExtService.findByUserId(periodical.getUserId());
		
		//根据查询出来期刊的状态选择页面上的下拉列表选项
		if("0".equals(periodical.getStatus())) {
			super.setRequestAttribute("uncheck", "selected");	//未审核
			super.setRequestAttribute("checked", "");	//已审核
			super.setRequestAttribute("reject", "");	//未通过
			super.setRequestAttribute("stop", null);	//停刊
		} else if("1".equals(periodical.getStatus())) {
			super.setRequestAttribute("uncheck", "");	//未审核
			super.setRequestAttribute("checked", "selected");	//已审核
			super.setRequestAttribute("reject", "");	//未通过
			super.setRequestAttribute("stop", "");	//停刊
		} else if("3".equals(periodical.getStatus())) {
			super.setRequestAttribute("uncheck", "");	//未审核
			super.setRequestAttribute("checked", "");	//已审核
			super.setRequestAttribute("reject", "selected");	//未通过
			super.setRequestAttribute("stop", "");	//停刊
		} else if("2".equals(periodical.getStatus())) {
			super.setRequestAttribute("uncheck", "");	//未审核
			super.setRequestAttribute("checked", "");	//已审核
			super.setRequestAttribute("reject", "");	//未通过
			super.setRequestAttribute("stop", "selected");	//停刊
		}
		
		super.setRequestAttribute("periodical", periodical);
		super.setRequestAttribute("userExt", userExt);
		super.setRequestAttribute("value", value);
		
		//判断是来自哪个页面的请求，
		//1表示查看，
		//2表示期刊列表的审核链接，指审核后返回所有期刊列表
		//3表示待审列表的审核链接,指在审核后返回未审核期刊列表
		if("1".equals(value)) {
			return "detail";
		} else if("2".equals(value) | "3".equals(value)) {
			return "update";
		} else if("4".equals(value)) {
			return "space";
		} else {
			return "error";
		}
	}
	
	//审核期刊，修改期刊的状态
	public String updateStatus() {
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		
		periodicalService.updateStatus(periodical.getStatus(), periodical.getPeriodicalId());
		
		if("2".equals(value)) {
			return "all";
		} else if("3".equals(value)) {
			return "uncheck";
		} else {
			return "error";
		}
	}

	//后台按主办单位搜索
	public String searchHostUnit() {
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		String ss = periodical.getHostUnit();
		String url = "periodical/periodicalHostUnit?periodical.hostUnit=" + ss + "&value=" + value + "&";
		pages = periodicalService.findByHostUnit((page-1)*10, url, ss, value);
		
		return "success";
	}
	
	//前台根据期刊分类查看期刊
	@SuppressWarnings("unchecked")
	public String findByCategory() {
		PerPeriodical perPeriodical = null;
		CategoryService categoryService = (CategoryService)SpringUtil.getBean("categoryService");
		int categoryId = periodical.getCategoryId();
		String url = "periodical/periodicalCategory?periodical.categoryId=" + categoryId + "&";
		
		//广告
		adsService = (AdsService) SpringUtil.getBean("adsService");
		ads_Category = adsService.findAdsByPosIdAndTime(3);//期刊分类广告 -----广告位id 3
		if(ads_Category == null){
			ads_Category = new Ads();
			ads_Category.setPicSrc("attached/images/adsPic.jpg");
			ads_Category.setUrl("javascript:void(0)");
		}
		
		//得到某期刊分类的所有期刊
		pages = periodicalService.findByCategory((page-1)*10, url, categoryId, "1");
		periodicals = pages.getRecords();
		//得到期刊的最新期刊期刊号及ID
		List<PerPeriodical> perPeriodicals = new ArrayList<PerPeriodical>();
		Map<String, Object> periodicalMap = null;
		
		for(int i=0; i<periodicals.size(); i++) {
			periodicalMap = (Map<String, Object>)periodicals.get(i);
			//得到某期刊已经发布的总期刊
			List<PerPeriodical> numbers = perPeriodicalService.findPerPeriodicalNumbers((Integer)periodicalMap.get("periodicalId"), "1");
			
			if(numbers.isEmpty()) {
				System.out.println("此期刊还没有发布期刊");
				continue;
			}
			
			try {
				//根据期刊ID、期刊号得到某一期期刊
				perPeriodical = perPeriodicalService.findByPeriodicalNum((Integer)periodicalMap.get("periodicalId"), numbers.get(0).getNumber());
			} catch (EmptyResultDataAccessException e) {
				System.out.println("此期刊还没有发布期刊");
				continue;
			}
			//将的期刊的名称、封面路径封装到periodical
			Periodical periodical = new Periodical();
			periodical.setCover((String)periodicalMap.get("cover"));
			periodical.setName((String)periodicalMap.get("name"));
			perPeriodical.setPeriodical(periodical);
			
			perPeriodicals.add(perPeriodical);
		}
		
		
		
		//得到左侧期刊分类
		List<Category> categorys = categoryService.findAll();
		Category category = categoryService.findById(categoryId);
		
		super.setRequestAttribute("perPeriodicals", perPeriodicals);
		super.setRequestAttribute("categorys", categorys);
		super.setRequestAttribute("category", category);
		
		return "success";
	}
	
	/**
	 * Desription 根据主编id获取该主编管理的所有期刊----下拉框使用ajax动态获取
	 * @author lwf
	 */
	public void getAllPerByChiefId(){
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		int editorChiefId = super.getUserIdBySession();
		List<Periodical> list = periodicalService.findByEditorChiefId(editorChiefId);
		Gson gson = new Gson();
		allPeriodicalInfo = gson.toJson(list);
		HttpServletResponse res = ServletActionContext.getResponse();   
		res.reset();   
		res.setContentType("text/html;charset=utf-8");   
		PrintWriter pw;
		try {
			pw = res.getWriter();
			pw.print(allPeriodicalInfo);
			pw.flush();   
			pw.close();  
		} catch (IOException e) {
			e.printStackTrace();
		}   
	}
	
	/**
	 * 异步请求-得到各种状态的期刊列表
	 * @author syb
	 * @return
	 */
	/*
	public String periodicalList() {
		periodicals = periodicalService.periodicalAll(value);
		dataMap.clear();
		dataMap.put("periodicals", periodicals);
		
		return "success";
	}
	*/
	
	/**
	 * Desription 根据登录用户的ID查询不同状态的期刊
	 * @author syb
	 */
	public String findByUserIdPStatus() {
		String url = "periodical/periodicalUserIdStatus?value=" + value + "&";
		periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");

		if("1".equals(value)) {	//value为表示查询的是审核已经通过的期刊，针对“我的期刊”
			pages = periodicalService.findByUserIdPStatus((page-1)*10, url, super.getUserIdBySession(), String.valueOf(value));
			return "success";
		} else if("2".equals(value)) {	//value为2表示查询的是状态为停刊、未通过的期刊，针对页面“其他”
			pages = periodicalService.findByUserId((page-1)*10, url, super.getUserIdBySession());
			return "other";
		} else {
			return "error";
		}
	}
	
	public String stopPublish() {
	    periodicalService.updateStatus("2", periodical.getPeriodicalId());
	    return SUCCESS;
	}
	
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public Periodical getPeriodical() {
		return periodical;
	}

	public void setPeriodical(Periodical periodical) {
		this.periodical = periodical;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

    public PeriodicalService getPeriodicalService() {
        return periodicalService;
    }
    @Resource(name="periodicalService")
    public void setPeriodicalService(PeriodicalService periodicalService) {
        this.periodicalService = periodicalService;
    }

    public List<Periodical> getPeriodicals() {
        return periodicals;
    }

    public void setPeriodicals(List<Periodical> periodicals) {
        this.periodicals = periodicals;
    }
	
    public List<Artical> getArticals() {
        return articals;
    }

    public void setArticals(List<Artical> articals) {
        this.articals = articals;
    }
    
    public ArticalService getArticalService() {
        return articalService;
    }
    @Resource(name="articalDao")
    public void setArticalService(ArticalService articalService) {
        this.articalService = articalService;
    }

	public String getAllPeriodicalInfo() {
		return allPeriodicalInfo;
	}

	public void setAllPeriodicalInfo(String allPeriodicalInfo) {
		this.allPeriodicalInfo = allPeriodicalInfo;
	}
    
	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}
	
	public PerPeriodicalService getPerPeriodicalService() {
		return perPeriodicalService;
	}
	@Resource(name="perPeriodicalService")
	public void setPerPeriodicalService(PerPeriodicalService perPeriodicalService) {
		this.perPeriodicalService = perPeriodicalService;
	}
	public Ads getAds_Category() {
		return ads_Category;
	}
	public void setAds_Category(Ads ads_Category) {
		this.ads_Category = ads_Category;
	}
}
